<?php
namespace M\Controller;
use Think\Controller;
class FoundingController extends CommonController {
    public function index(){
        $site_title = "众测天下";
        $this->assign('site_title', $site_title);
        $this->display();
    }
    
    
    /*
     * 项目详情页面show_thirdparty_data_of_app
     */
    public function detail() {
        /*
         * Date: 2015-12-16
         * 增加一个判断是否是关注用户
         * 
         */
        redirect(U("detail_new",array('specialid'=>I('get.specialid'),'fdid'=>I('get.fdid'))));
//        $member = $this->memberinfo;
//        print_r(session('openid'));
        
        $openid = session('openid');
        
        $DB_openid = M("members_subscribe_records");
        $map_openid['openid']=$openid;
        $map_openid['issubscribe']=1;
        $res_openid = $DB_openid->where($map_openid)->find();
//        print_r($DB_openid->getLastSql());
//        print_r($res_openid);
//        exit();
        if(empty($res_openid))
        {
            $this->assign('issubscribe', 0);
        }
        else
        {
            $this->assign('issubscribe', 1);
        }
//        print_r($res_openid);
//        exit();
        /*
         * Date: 2015-12-15
         * 增加一个判断是否是专题来源
         * 
         */
        $specialid = trim(I("get.specialid"));
        
        if(empty($specialid))
        {
            $specialid=0;
        }
        
        $this->assign("specialid", $specialid);
        /*
         * 增加一个判断是否是专题来源 end
         */
        
        $fdid = trim(I('get.fdid'));
        if(!empty($fdid))
        {
           $DB = M('fundings');
           $res = $DB->find($fdid);
           
           if(!empty($res))
           {
               //获取微信分享资料
               $this->get_weixin_jssdk_config();
               
               $res['membername']=  $this->get_name_by_mid($res['mid']);
               $res['institution'] = $this->get_name_by_institutionid($res['institutionid']);
               $res['packagename']=  $this->get_name_by_packageid($res['packageid']);
               $res['category']=  $this->get_name_by_sortid($res['first_categoryid']);
               $res['finish']=$res['finish']*0.01;
               $res['emoney']=($res['emoney']*0.01);
               
               $res['location'] = mb_substr($res['location'], 0,14,'utf-8')."...";
               
               
               
               
               //获取赞助列表
               $DB_sponsor = M('fundings_sponsor');
               $map['status']=1;
               $map['fid']=$fdid;
               
               $sponsor_res =$DB_sponsor->where($map)->join("LEFT JOIN `fd_members` ON `fd_fundings_sponsor`.mid = `fd_members`.id")->order('paytime DESC')->limit(10)->select();
               $sponsor_res_count =$DB_sponsor->where($map)->count();
//               $sponsor_res_count = count($sponsor_res);
               
//               print_r($DB_sponsor->getLastSql());
               
               
               foreach ($sponsor_res as $key => $value) {
                   $sponsor_res[$key]['username'] = $this->get_name_by_mid($value['mid']);
                   $sponsor_res[$key]['money'] = $value['money']*0.01; 
               }
               
               /*
                * 计算达成率，保留两位小数
                */
               $total_fee = $res['emoney']+$res['smoney']*$res['samnum']*0.01;
//               echo $res['emoney'];
//               echo "<br/>";
//               echo $res['smoney']*$res['samnum']*0.01;
//               echo "<br/>";
//               print_r($total_fee);
//               exit();
               $rate =  round($res['finish']*100/$total_fee,2);
               
               /*
                * 判断项目的状态，已经完成的，需要调出产品的检测报告
                */
               if($res['state']==3)
               {
                   $testreport = $this->_get_founding_report($res['testreportid']);
                   $res['testreport_pdf']=$testreport['download'];
                   $res['testreport_jpg']=$testreport['download_jpg'];
                   
                   $sample = $this->_get_founding_sample($res['sampleid']);
                   $res['sample_url']=$sample['img_url'];
//                   print_r($sample);
               }
               
               /*
                * 判断分享的配图是否存在，不存在用默认的来代替
                */
//               $founding_share_img = "http://".I('server.HTTP_HOST')."/".$res['thumb'];
               
//               
//               echo $res['finish'];
//               echo "<br/>";
//               echo $total_fee;
//               echo "<br/>";
//               print_r($rate);
               
               $this->assign('total_fee', $total_fee);
               $this->assign('rate', $rate);
               $this->assign('fd_info', $res);
               
               $this->assign('sponsors', $sponsor_res);
               $this->assign('sponsors_count', $sponsor_res_count);
               $this->assign('fdid', $fdid);
               $this->display(); 
           }
           else
           {
               redirect(U('M/Index/index'));
           }


            
        }
        else
        {
            redirect(U('M/Index/index'));
            
        }
        
    }
    
    /*
     * 项目详情的新版
     * 
     * 需要获取的资料有：
     * // 1. 产品的展示图片  
     * // 2. 用户信息（头像、姓名、发起时间
     * // 3. 项目发起时间 --
     * // 4. 已筹金额  --
     * // 5. 目标金额  --
     * // 6. 参与人数
     * // 7. 项目状态  --
     * // 8. 最多6个的最新支持者
     * // 9. 众测故事  --
     * // 10.检查详情入口 --
     * // 11. 支持者（最近的金钱高到低）
     * // 12.精彩评论
     * // 13. 评论总数
     * // 14. 更多评论入口
     * // 15. 分享按钮  --
     * // 16. 立刻参与按钮  --
     * // 17. 是否收藏了该项目
     * 
     */
    
    
    
    
    public function detail_new() {
        /*
         * Date: 2015-12-16
         * 增加一个判断是否是关注用户
         * 
         */
//        判断数据来源
        $from_channel = I('get.from_channel');
        $this->assign("from_channel", $from_channel);
        
//        $member = $this->memberinfo;
//        print_r(session('openid'));
        
        $openid = session('openid');
        
        $DB_openid = M("members_subscribe_records");
        $map_openid['openid']=$openid;
        $map_openid['issubscribe']=1;
        $res_openid = $DB_openid->where($map_openid)->find();
//        print_r($DB_openid->getLastSql());
//        print_r($res_openid);
//        exit();
        if(empty($res_openid))
        {
            $this->assign('issubscribe', 0);
        }
        else
        {
            $this->assign('issubscribe', 1);
        }
//        print_r($res_openid);
//        exit();
        /*
         * Date: 2015-12-15
         * 增加一个判断是否是专题来源
         * 
         */
        $specialid = trim(I("get.specialid"));
        
        if(empty($specialid))
        {
            $specialid=0;
        }
        
        $this->assign("specialid", $specialid);
        /*
         * 增加一个判断是否是专题来源 end
         */
        
        $fdid = trim(I('get.fdid'));
        if(!empty($fdid))
        {
           $DB = M('fundings');
           $res = $DB->find($fdid);
           
           if(!empty($res))
           {
               //获取微信分享资料
               $this->get_weixin_jssdk_config();
               
               //1. 产品的展示图片
               if(empty($res['detail_thumb']))
                {
                    $res['thumb_list']=  $this->get_one_thumb_list($res['member_upload_imgs']);
                }
                else
                {
                    $res['thumb_list']=  $this->get_one_thumb_list($res['detail_thumb']);
                }
//               $res['thumb_list'] = $this->get_one_thumb_list($res['detail_thumb']);
//               print_r($res);
               $res['thumb_list_count']=count($res['thumb_list']);
               
               // 2. 用户信息（头像、姓名、发起时间
               $res['username']=$this->_get_member_nickname($res['mid']);
               $res['avatar']=  $this->_get_one_avatar($res['mid']);
//               print_r($res);
               
            // 3. 项目发起时间 --
            // 4. 已筹金额  --
            // 5. 目标金额  --
               
               
            /* // 6. 参与人数
             * 
            * // 7. 项目状态  --
            * // 8. 最多6个的最新支持者
            * // 9. 众测故事  --
            * // 10.检查详情入口 --
            * // 11. 支持者（最近的金钱高到低）
            * // 12.精彩评论
            * // 13. 评论总数
            * // 14. 更多评论入口
            * // 15. 分享按钮  --
            * // 16. 立刻参与按钮  --
            * // 17. 是否收藏了该项目
            * 
            */
               // 6. 参与人数
               $res['sponsor_count']=  $this->_get_founding_sponsor_count($fdid);
               
               
               // 8. 最多6个的最新支持者
               $res['latest_six_sponsors']=  $this->_get_one_lastest_six_sponsors($fdid);
               
               // 11. 支持者（最近的金钱高到低）
                $res['hot_sponsors']=  $this->_get_one_most_sponsors($fdid);
//                print_r($res);
                $res['sponsors_count']=  $this->_get_one_sponsor_count($fdid);
                //热门评论
                $res['comment_count']=  $this->_get_one_comments_count($fdid);
                $res['hot_comments']=  $this->_get_one_hot_comments($fdid,1);
                
               
               $res['membername']=  $this->get_name_by_mid($res['mid']);
               $res['institution'] = $this->get_name_by_institutionid($res['institutionid']);
               $res['packagename']=  $this->get_name_by_packageid($res['packageid']);
               $res['category']=  $this->get_name_by_sortid($res['first_categoryid']);
               $res['finish']=$res['finish']*0.01;
               $res['emoney']=($res['emoney']*0.01);
               
               $res['location'] = mb_substr($res['location'], 0,14,'utf-8')."...";
               
               $res['ifcollection'] = $this->_chk_if_member_follow_founding(session("mid"), $fdid, 1);
               
               
//               print_r($res);
//               exit();
               
               
               //获取赞助列表
               $DB_sponsor = M('fundings_sponsor');
               $map['status']=1;
               $map['fid']=$fdid;
               
               $sponsor_res =$DB_sponsor->where($map)->join("LEFT JOIN `fd_members` ON `fd_fundings_sponsor`.mid = `fd_members`.id")->order('paytime DESC')->limit(10)->select();
               $sponsor_res_count =$DB_sponsor->where($map)->count();
//               $sponsor_res_count = count($sponsor_res);
               
//               print_r($DB_sponsor->getLastSql());
               
               
               foreach ($sponsor_res as $key => $value) {
                   $sponsor_res[$key]['username'] = $this->get_name_by_mid($value['mid']);
                   $sponsor_res[$key]['money'] = $value['money']*0.01; 
               }
               
               /*
                * 计算达成率，保留两位小数
                */
               $total_fee = $res['emoney']+$res['smoney']*$res['samnum']*0.01;
//               echo $res['emoney'];
//               echo "<br/>";
//               echo $res['smoney']*$res['samnum']*0.01;
//               echo "<br/>";
//               print_r($total_fee);
//               exit();
               $rate =  round($res['finish']*100/$total_fee,2);
               
               /*
                * 判断项目的状态，已经完成的，需要调出产品的检测报告
                */
               if($res['state']==3)
               {
                   $testreport = $this->_get_founding_report($res['testreportid']);
                   $res['testreport_pdf']=$testreport['download'];
                   $res['testreport_jpg']=$testreport['download_jpg'];
                   
                   $sample = $this->_get_founding_sample($res['sampleid']);
                   $res['sample_url']=$sample['img_url'];
//                   print_r($sample);
               }
               
               /*
                * 判断分享的配图是否存在，不存在用默认的来代替
                */
//               $founding_share_img = "http://".I('server.HTTP_HOST')."/".$res['thumb'];
               
//               
//               echo $res['finish'];
//               echo "<br/>";
//               echo $total_fee;
//               echo "<br/>";
//               print_r($rate);
               
               $this->assign('total_fee', $total_fee);
               $this->assign('rate', $rate);
               $this->assign('fd_info', $res);
               $this->assign('mid', session("mid"));
               $this->assign('sponsors', $sponsor_res);
               $this->assign('sponsors_count', $sponsor_res_count);
               $this->assign('fdid', $fdid);
               
//               print_r($res);
//               exit();
               
               $this->display(); 
           }
           else
           {
               redirect(U('M/Index/index'));
           }


            
        }
        else
        {
            redirect(U('M/Index/index'));
            
        }
        
    }
    
    
    /*
     * 支持成功后的页面
     */
    public function detail_new_after_payment() {
        /*
         * Date: 2015-12-16
         * 增加一个判断是否是关注用户
         * 
         */
        
//        $member = $this->memberinfo;
//        print_r(session('openid'));
        
        $openid = session('openid');
        
        
        //获取来源的红包参数
        $random_code = I("get.random_code");
        $this->assign('random_code',$random_code);
        
        $DB_openid = M("members_subscribe_records");
        $map_openid['openid']=$openid;
        $map_openid['issubscribe']=1;
        $res_openid = $DB_openid->where($map_openid)->find();
//        print_r($DB_openid->getLastSql());
//        print_r($res_openid);
//        exit();
        if(empty($res_openid))
        {
            $this->assign('issubscribe', 0);
        }
        else
        {
            $this->assign('issubscribe', 1);
        }
//        print_r($res_openid);
//        exit();
        /*
         * Date: 2015-12-15
         * 增加一个判断是否是专题来源
         * 
         */
        $specialid = trim(I("get.specialid"));
        
        if(empty($specialid))
        {
            $specialid=0;
        }
        
        $this->assign("specialid", $specialid);
        /*
         * 增加一个判断是否是专题来源 end
         */
        
        $fdid = trim(I('get.fdid'));
        if(!empty($fdid))
        {
           $DB = M('fundings');
           $res = $DB->find($fdid);
           
           if(!empty($res))
           {
               /*
                * 检查是否有红包领取
                * 
                * 
                */
               
               if($this->_chk_if_can_get_redpack($openid, $fid, $create_mid))
               {
                   $this->assign('show_redpack_window', 1);
               }
               else
               {
                   $this->assign('show_redpack_window', 0);
               }
               
               
               //获取微信分享资料
               $this->get_weixin_jssdk_config();
               
               //1. 产品的展示图片
               
//               $res['thumb_list'] = $this->get_one_thumb_list($res['detail_thumb']);
               if(empty($res['detail_thumb']))
                {
                    $res['thumb_list']=  $this->get_one_thumb_list($res['member_upload_imgs']);
                }
                else
                {
                    $res['thumb_list']=  $this->get_one_thumb_list($res['detail_thumb']);
                }
//               print_r($res);
               $res['thumb_list_count']=count($res['thumb_list']);
               
               // 2. 用户信息（头像、姓名、发起时间
               $res['username']=$this->_get_member_nickname($res['mid']);
               $res['avatar']=  $this->_get_one_avatar($res['mid']);
//               print_r($res);
               
            // 3. 项目发起时间 --
            // 4. 已筹金额  --
            // 5. 目标金额  --
               
               
            /* // 6. 参与人数
             * 
            * // 7. 项目状态  --
            * // 8. 最多6个的最新支持者
            * // 9. 众测故事  --
            * // 10.检查详情入口 --
            * // 11. 支持者（最近的金钱高到低）
            * // 12.精彩评论
            * // 13. 评论总数
            * // 14. 更多评论入口
            * // 15. 分享按钮  --
            * // 16. 立刻参与按钮  --
            * // 17. 是否收藏了该项目
            * 
            */
               // 6. 参与人数
               $res['sponsor_count']=  $this->_get_founding_sponsor_count($fdid);
               
               
               // 8. 最多6个的最新支持者
               $res['latest_six_sponsors']=  $this->_get_one_lastest_six_sponsors($fdid);
               
               // 11. 支持者（最近的金钱高到低）
                $res['hot_sponsors']=  $this->_get_one_most_sponsors($fdid);
//                print_r($res);
                $res['sponsors_count']=  $this->_get_one_sponsor_count($fdid);
                //热门评论
                $res['comment_count']=  $this->_get_one_comments_count($fdid);
                $res['hot_comments']=  $this->_get_one_hot_comments($fdid,1); 
               
               
               $res['membername']=  $this->get_name_by_mid($res['mid']);
               $res['institution'] = $this->get_name_by_institutionid($res['institutionid']);
               $res['packagename']=  $this->get_name_by_packageid($res['packageid']);
               $res['category']=  $this->get_name_by_sortid($res['first_categoryid']);
               $res['finish']=$res['finish']*0.01;
               $res['emoney']=($res['emoney']*0.01);
               
               $res['location'] = mb_substr($res['location'], 0,14,'utf-8')."...";
               
               $res['ifcollection'] = $this->_chk_if_member_follow_founding(session("mid"), $fdid, 1);
               
               
//               print_r($res);
//               exit();
               
               
               //获取赞助列表
               $DB_sponsor = M('fundings_sponsor');
               $map['status']=1;
               $map['fid']=$fdid;
               
               $sponsor_res =$DB_sponsor->where($map)->join("LEFT JOIN `fd_members` ON `fd_fundings_sponsor`.mid = `fd_members`.id")->order('paytime DESC')->limit(10)->select();
               $sponsor_res_count =$DB_sponsor->where($map)->count();
//               $sponsor_res_count = count($sponsor_res);
               
//               print_r($DB_sponsor->getLastSql());
               
               
               foreach ($sponsor_res as $key => $value) {
                   $sponsor_res[$key]['username'] = $this->get_name_by_mid($value['mid']);
                   $sponsor_res[$key]['money'] = $value['money']*0.01; 
               }
               
               /*
                * 计算达成率，保留两位小数
                */
               $total_fee = $res['emoney']+$res['smoney']*$res['samnum']*0.01;
//               echo $res['emoney'];
//               echo "<br/>";
//               echo $res['smoney']*$res['samnum']*0.01;
//               echo "<br/>";
//               print_r($total_fee);
//               exit();
               $rate =  round($res['finish']*100/$total_fee,2);
               
               /*
                * 判断项目的状态，已经完成的，需要调出产品的检测报告
                */
               if($res['state']==3)
               {
                   $testreport = $this->_get_founding_report($res['testreportid']);
                   $res['testreport_pdf']=$testreport['download'];
                   $res['testreport_jpg']=$testreport['download_jpg'];
                   
                   $sample = $this->_get_founding_sample($res['sampleid']);
                   $res['sample_url']=$sample['img_url'];
//                   print_r($sample);
               }
               
               /*
                * 判断分享的配图是否存在，不存在用默认的来代替
                */
//               $founding_share_img = "http://".I('server.HTTP_HOST')."/".$res['thumb'];
               
//               
//               echo $res['finish'];
//               echo "<br/>";
//               echo $total_fee;
//               echo "<br/>";
//               print_r($rate);
               
               $this->assign('total_fee', $total_fee);
               $this->assign('rate', $rate);
               $this->assign('fd_info', $res);
               $this->assign('mid', session('mid'));
               $this->assign('sponsors', $sponsor_res);
               $this->assign('sponsors_count', $sponsor_res_count);
               $this->assign('fdid', $fdid);
               $this->display(); 
           }
           else
           {
               redirect(U('M/Index/index'));
           }


            
        }
        else
        {
            redirect(U('M/Index/index'));
            
        }
        
    }
    
    
    public function detail_of_share() {
        /*
         * Date: 2015-12-16
         * 增加一个判断是否是关注用户
         * 
         */
        
//        $member = $this->memberinfo;
//        print_r(session('openid'));
        $fdid = trim(I('get.fdid'));
        $openid = session('openid');
//        $mid = session("mid");
        
        //获取来源的红包参数
        $random_code = I("get.random_code");
        
        if(!empty($random_code))
        {
            $this->assign('random_code',$random_code);
//            获取该random_code 资料
            $res_redpack_create_param = M("redpack_create_param")->where(array('random_code'=>$random_code))->find();
            
            
//            判断是否可以领取红包
            if($this->_chk_if_can_get_redpack($openid, $fdid, $res_redpack_create_param['openid']))
            {
//                $this->assign('if_show_redpack_div', 1);
                //生成可领取的红包
                $redpack_code = $this->_create_random_code(20);
                $rp_id = $this->_create_redpack_records($random_code, $redpack_code,$fdid);
            }
            else
            {
//                $this->assign('if_show_redpack_div', 0);
                 $this->assign('random_code',0);
                $rp_id = 0;
            }
            
            
            
        }
        else
        {
            $this->assign('random_code',0);
            $rp_id = 0;
        }
        
        
        if(!empty($rp_id))
        {
            $this->assign("if_show_redpack_div", 1);
        }
        else
        {
            $this->assign("if_show_redpack_div", 0);
        }
        
        $this->assign("rp_id", $rp_id);
        
        
        
        
        
        $DB_openid = M("members_subscribe_records");
        $map_openid['openid']=$openid;
        $map_openid['issubscribe']=1;
        $res_openid = $DB_openid->where($map_openid)->find();
//        print_r($DB_openid->getLastSql());
//        print_r($res_openid);
//        exit();
        if(empty($res_openid))
        {
            $this->assign('issubscribe', 0);
        }
        else
        {
            $this->assign('issubscribe', 1);
        }
//        print_r($res_openid);
//        exit();
        /*
         * Date: 2015-12-15
         * 增加一个判断是否是专题来源
         * 
         */
        $specialid = trim(I("get.specialid"));
        
        if(empty($specialid))
        {
            $specialid=0;
        }
        
        $this->assign("specialid", $specialid);
        /*
         * 增加一个判断是否是专题来源 end
         */
        
        
        if(!empty($fdid))
        {
           $DB = M('fundings');
           $res = $DB->find($fdid);
           
           if(!empty($res))
           {
               //获取微信分享资料
               $this->get_weixin_jssdk_config();
               
               //1. 产品的展示图片
               if(empty($res['detail_thumb']))
                {
                    $res['thumb_list']=  $this->get_one_thumb_list($res['member_upload_imgs']);
                }
                else
                {
                    $res['thumb_list']=  $this->get_one_thumb_list($res['detail_thumb']);
                }
//               $res['thumb_list'] = $this->get_one_thumb_list($res['detail_thumb']);
//               print_r($res);
               $res['thumb_list_count']=count($res['thumb_list']);
               
               // 2. 用户信息（头像、姓名、发起时间
               $res['username']=$this->_get_member_nickname($res['mid']);
               $res['avatar']=  $this->_get_one_avatar($res['mid']);
//               print_r($res);
               
            // 3. 项目发起时间 --
            // 4. 已筹金额  --
            // 5. 目标金额  --
               
               
            /* // 6. 参与人数
             * 
            * // 7. 项目状态  --
            * // 8. 最多6个的最新支持者
            * // 9. 众测故事  --
            * // 10.检查详情入口 --
            * // 11. 支持者（最近的金钱高到低）
            * // 12.精彩评论
            * // 13. 评论总数
            * // 14. 更多评论入口
            * // 15. 分享按钮  --
            * // 16. 立刻参与按钮  --
            * // 17. 是否收藏了该项目
            * 
            */
               // 6. 参与人数
               $res['sponsor_count']=  $this->_get_founding_sponsor_count($fdid);
               
               
               // 8. 最多6个的最新支持者
               $res['latest_six_sponsors']=  $this->_get_one_lastest_six_sponsors($fdid);
               
               // 11. 支持者（最近的金钱高到低）
                $res['hot_sponsors']=  $this->_get_one_most_sponsors($fdid);
//                print_r($res);
                $res['sponsors_count']=  $this->_get_one_sponsor_count($fdid);
                //热门评论
                $res['comment_count']=  $this->_get_one_comments_count($fdid);
                $res['hot_comments']=  $this->_get_one_hot_comments($fdid,1);
                
               
               $res['membername']=  $this->get_name_by_mid($res['mid']);
               $res['institution'] = $this->get_name_by_institutionid($res['institutionid']);
               $res['packagename']=  $this->get_name_by_packageid($res['packageid']);
               $res['category']=  $this->get_name_by_sortid($res['first_categoryid']);
               $res['finish']=$res['finish']*0.01;
               $res['emoney']=($res['emoney']*0.01);
               
               $res['location'] = mb_substr($res['location'], 0,14,'utf-8')."...";
               
               $res['ifcollection'] = $this->_chk_if_member_follow_founding(session("mid"), $fdid, 1);
               
               
//               print_r($res);
//               exit();
               
               
               //获取赞助列表
               $DB_sponsor = M('fundings_sponsor');
               $map['status']=1;
               $map['fid']=$fdid;
               
               $sponsor_res =$DB_sponsor->where($map)->join("LEFT JOIN `fd_members` ON `fd_fundings_sponsor`.mid = `fd_members`.id")->order('paytime DESC')->limit(10)->select();
               $sponsor_res_count =$DB_sponsor->where($map)->count();
//               $sponsor_res_count = count($sponsor_res);
               
//               print_r($DB_sponsor->getLastSql());
               
               
               foreach ($sponsor_res as $key => $value) {
                   $sponsor_res[$key]['username'] = $this->get_name_by_mid($value['mid']);
                   $sponsor_res[$key]['money'] = $value['money']*0.01; 
               }
               
               /*
                * 计算达成率，保留两位小数
                */
               $total_fee = $res['emoney']+$res['smoney']*$res['samnum']*0.01;
//               echo $res['emoney'];
//               echo "<br/>";
//               echo $res['smoney']*$res['samnum']*0.01;
//               echo "<br/>";
//               print_r($total_fee);
//               exit();
               $rate =  round($res['finish']*100/$total_fee,2);
               
               /*
                * 判断项目的状态，已经完成的，需要调出产品的检测报告
                */
               if($res['state']==3)
               {
                   $testreport = $this->_get_founding_report($res['testreportid']);
                   $res['testreport_pdf']=$testreport['download'];
                   $res['testreport_jpg']=$testreport['download_jpg'];
                   
                   $sample = $this->_get_founding_sample($res['sampleid']);
                   $res['sample_url']=$sample['img_url'];
//                   print_r($sample);
               }
               
               /*
                * 判断分享的配图是否存在，不存在用默认的来代替
                */
//               $founding_share_img = "http://".I('server.HTTP_HOST')."/".$res['thumb'];
               
//               
//               echo $res['finish'];
//               echo "<br/>";
//               echo $total_fee;
//               echo "<br/>";
//               print_r($rate);
               
               $this->assign('total_fee', $total_fee);
               $this->assign('rate', $rate);
               $this->assign('fd_info', $res);
               $this->assign('mid', session("mid"));
               $this->assign('sponsors', $sponsor_res);
               $this->assign('sponsors_count', $sponsor_res_count);
               $this->assign('fdid', $fdid);
               $this->display(); 
               
//               print_r($res);
           }
           else
           {
               redirect(U('M/Index/index'));
           }


            
        }
        else
        {
            redirect(U('M/Index/index'));
            
        }
        
    }
    
    /*
     * 检测详情
     */
    public function detail_of_testing() {
        $fdid = I('get.fdid');
        if(!empty($fdid))
        {
           $DB = M('fundings');
           $res = $DB->find($fdid);
           
           if(!empty($res))
           {
//               检测机构
               $res['institution'] = $this->get_name_by_institutionid($res['institutionid']);
//               检测内容
               $res['packagename']=  $this->get_name_by_packageid($res['packageid']);
//               危害介绍
               $package_arr = explode(",", $res['packageid']);
                foreach ($package_arr as $key => $value) {
                    $result[$key]=  $this->get_package_by_id($value);
                }
                $res['dangers']=  $result;
                
                //获取封面图片
                $res['sample_img']=  $this->get_cover_of_samples($fdid);
                $res['testreport_img']=  $this->get_cover_of_testreport($fdid);
                
           }
           
        }
        
        $this->assign('result', $res);
        $this->display();
    }
    
    /*
     * 获取更多的项目赞助者
     */
    public function get_sponor_by_page() {
        $fdid = trim(I('get.fdid'));
        $pagecount = I('get.pagecount');
        if(empty($pagecount))
        {
            $pagecount=0;
        }
        
        $startcount = $pagecount*10;
//        $DB = M('fundings');
//        $res = $DB->find($fdid);
        
        $DB_sponsor = M('fundings_sponsor');
        $map['status']=1;
        $map['fid']=$fdid;

        $sponsor_res =$DB_sponsor->where($map)->join("LEFT JOIN `fd_members` ON `fd_fundings_sponsor`.mid = `fd_members`.id")->order('paytime DESC')->limit($startcount,10)->select();
//        exit($DB_sponsor->getLastSql());
        
        if(!empty($sponsor_res))
        {
            foreach ($sponsor_res as $key => $value) {
                $sponsor_res[$key]['paytime_format']=date("Y-m-d H:i",$value['paytime']);
                $sponsor_res[$key]['money']=$value['money']/100;
            }
            $result['res']=$sponsor_res;
            $result['err']=0;
            $result['msg']="成功获取数据";
        }
        else
        {
            $result['err']=1;
            $result['msg']="暂无更多数据";
        }
        
        
        echo json_encode($result);
    }
    
    /*
     * 获取项目详情下的检测内容危害
     * 
     */
    public function founding_package_detail() {
        $fdid = I('get.fdid');
        $DB = M("fundings");
        
        $res = $DB->find($fdid);
        
        $package_arr = explode(",", $res['packageid']);
//        print_r($package_arr);
        foreach ($package_arr as $key => $value) {
            $resuslt[$key]=  $this->get_package_by_id($value);
        }
        
        $this->assign("packages", $resuslt);
        $this->display();
    }
    
    /*
     * 获取指定的产品下的项目列表情况
     */
    public function product_foundings() {
        $pid = I('get.pid');
        
        $DB= M('fundings');
        
        $map['pid']=$pid;
        $res = $DB->where($map)->select();
        foreach ($res as $key => $value) {
            $res[$key]['institution'] = $this->get_name_by_institutionid($value['institutionid']);
        }
        $this->assign('fundings',$res);
        $this->display();
        
    }
    
    
    
    /*
     * Date: 2015-10-19
     * Des: 发起众筹
     */

    
    public function publish() {
        
        if(IS_POST)
        {
            //提交数据
            $pdname = I('post.pdname');
            $brand = I('post.brand');
            $batch = I('post.batch');
            $citycode = I('post.citycode');
            $packageid = I('post.packageid');
            $institutionid = I('post.institutionid');
            $first_categoryid = I('post.first_categoryid');
            $emoney = I('post.emoney');
            $fromtype = 0;
            $content = I('post.content');
            
            $memberinfo = $this->memberinfo;
            
            
            $data['pjname']=$pdname."检测";
            $data['pdname']=$pdname;
            $data['brand']=$brand;
            $data['citycode']=$citycode;
            
             /*
             * Date:2015-11-30
             * 增加的字段
             */
            $location_detail = I('post.location_detail');
            
            $cityname = $this->get_cityname_by_citycode($citycode);
            
            $data['location'] = $cityname.$location_detail;
            $data['first_categoryid']=$first_categoryid;
            $data['packageid']=$packageid;
            $data['institutionid']=$institutionid;
            $data['ctime']=I('server.REQUEST_TIME');
            $data['btime']=I('server.REQUEST_TIME');
            $data['content']=$content;
            $data['emoney']=$emoney*100;
            $data['fromtype']=$fromtype;
            $data['mid']=$memberinfo['id'];
            $data['batch']=$batch;
            $data['rawdata'] = serialize($_POST);
            
            //存入微信接口的图片数据
            $wx_media_ids = I('post.wx_media_ids');
            /*
             * 根据media id 来下载图片到本地数据库
             */
            if(!empty($wx_media_ids))
            {
                $accessToken = $this->accessToken;
                    
                $wx_media_arr = json_decode(htmlspecialchars_decode($wx_media_ids),true);
                $sampleids = "";
                
                foreach ($wx_media_arr as $key => $value) {
                    $filename = date('YmdHis').$this->random_code().'.jpg';
                    $targetName = "./Uploads/fundings/wx_media/".$filename;
                    $ch = curl_init("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$accessToken&media_id=$value");
                    $fp = fopen($targetName, 'wb');
                    curl_setopt($ch, CURLOPT_FILE, $fp);
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_exec($ch);
                    curl_close($ch);
                    fclose($fp);
                    
                    /*
                     * 插入记录
                     * 1. 插入到 image 表 并得到返回的id写入 sampleid
                     */
                   $id[$key] = $this->insert_image(substr($targetName, 1));
                   $sampleids .=$id[$key].",";
                    
                    
                }
            
                //用户前端上传的图片保存位置
                $data['member_upload_imgs'] = substr($sampleids, 0,-1);
                
                $data['wx_media_ids']=serialize(I('post.wx_media_ids'));
            }
            
            
            
           
            
            /*
             * Date: 2011-11-16
             * 临时调整为可以发起就为审核中
             */
//            $data['state']=1;

            
            $DB = M('fundings');
            $id = $DB->add($data);

            if($id)
            {
                $this->success('添加成功');
                //跳转到支付页面
                redirect(U('Founding/publish_pay_money',array('fdid'=>$id)));
            }
            else
            {
//                print_r($DB->getLastSql());
                $this->error('添加失败');
            }
            
            
        }
        else
        {
            
            /*
             * 跳转到 新的地址
             */
            
            redirect(U('M/Founding/publish_new',array('from'=>1,'isnew'=>1)));
            
            exit();
            /*
             * 加载选择的套餐信息
             */
            $from = I('get.from');
            if(empty($from))
            {
                $from =0;
                
            }
            $this->assign('from', $from);
            
            $packages = M('fundings_package')->select();
            foreach ($packages as $key => $value) {
                $packages[$key]['price'] = $value['price']*0.01;
            }
            $this->assign('packages', $packages);
            /*
             * 加载检测机构信息
             */
            $institutions = M('institution')->select();
            $this->assign('institutions', $institutions);
            
            
            $this->display();
        }
    }
    
    public function publish_new() {
        if(IS_POST)
        {
            //提交数据
            $pdname = I('post.pdname');
            $brand = I('post.brand');
            $batch = I('post.batch');
            $citycode = I('post.citycode');
            $packageid = I('post.packageid');
            $institutionid = I('post.institutionid');
            $first_categoryid = I('post.first_categoryid');
            $emoney = I('post.emoney');
            $fromtype = 0;
            $content = I('post.content');
            
            $memberinfo = $this->memberinfo;
            
            
            $data['pjname']=$pdname."检测";
            $data['pdname']=$pdname;
            $data['brand']=$brand;
            $data['citycode']=$citycode;
            
             /*
             * Date:2015-11-30
             * 增加的字段
             */
            $location_detail = I('post.location_detail');
            
            $cityname = $this->get_cityname_by_citycode($citycode);
            
            $data['location'] = $cityname.$location_detail;
            $data['first_categoryid']=$first_categoryid;
            $data['packageid']=$packageid;
            $data['institutionid']=$institutionid;
            $data['ctime']=I('server.REQUEST_TIME');
            $data['btime']=I('server.REQUEST_TIME');
            $data['content']=$content;
            $data['emoney']=$emoney*100;
            $data['fromtype']=$fromtype;
            $data['mid']=$memberinfo['id'];
            $data['batch']=$batch;
            $data['rawdata'] = serialize($_POST);
            
            //存入微信接口的图片数据
            $wx_media_ids = I('post.wx_media_ids');
            /*
             * 根据media id 来下载图片到本地数据库
             */
            if(!empty($wx_media_ids))
            {
                $accessToken = $this->accessToken;
                    
                $wx_media_arr = json_decode(htmlspecialchars_decode($wx_media_ids),true);
                $sampleids = "";
                $targetName_arr = array();
                foreach ($wx_media_arr as $key => $value) {
                    $filename = date('YmdHis').$this->random_code().'.jpg';
                    $targetName = "./Uploads/fundings/wx_media/".$filename;
                    
                    array_push($targetName_arr, $targetName);
                    
                    $ch = curl_init("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$accessToken&media_id=$value");
                    $fp = fopen($targetName, 'wb');
                    curl_setopt($ch, CURLOPT_FILE, $fp);
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_exec($ch);
                    curl_close($ch);
                    fclose($fp);
                    
                    /*
                     * 插入记录
                     * 1. 插入到 image 表 并得到返回的id写入 sampleid
                     */
                   $id[$key] = $this->insert_image(substr($targetName, 1));
                   $sampleids .=$id[$key].",";
                    
                    
                }
            
                //用户前端上传的图片保存位置
                $data['member_upload_imgs'] = substr($sampleids, 0,-1);
                $data['detail_thumb'] = $data['member_upload_imgs'];
                
                $data['wx_media_ids']=serialize(I('post.wx_media_ids'));
                
                /*
                * 处理第一张图片就是默认的图片
                */
//               print_r($targetName_arr);
//               exit();
               if(!empty($targetName_arr))
               {
                   $data['thumb']=  substr($targetName_arr[0], 1);
                   $data['mini_thumb']=substr($targetName_arr[0], 1);
               }
            }
            
            
            
            
           
            
            /*
             * Date: 2011-11-16
             * 临时调整为可以发起就为审核中
             */
//            $data['state']=1;

            
            $DB = M('fundings');
            $id = $DB->add($data);

            if($id)
            {
//                $this->success('添加成功');
                //跳转到支付页面
                redirect(U('Founding/publish_pay_money',array('fdid'=>$id)));
            }
            else
            {
//                print_r($DB->getLastSql());
                $this->error('添加失败');
            }
            
            
        }
        else
        {
           /*
             * 加载选择的套餐信息
             */
            $from = I('get.from');
            if(empty($from))
            {
                $from =0;
                
            }
            $this->assign('from', $from);
            
            $packages = M('fundings_package')->select();
            foreach ($packages as $key => $value) {
                $packages[$key]['price'] = $value['price']*0.01;
            }
            $this->assign('packages', $packages);
            /*
             * 加载检测机构信息
             */
            $institutions = M('institution')->select();
            $this->assign('institutions', $institutions);
            
            
            /*
             *  判断是否是新发起的项目 
             */
            $isnew = I("get.isnew");
            
            if(!empty($isnew)&& ($isnew==1))
            {
                /*
                * 获取默认推荐的产品分类信息
                * 
                * 获取默认的检查内容 和 检测机构信息
                */

               $map['pid']=0;  //获取大类
               $map['name']="其它食品";

               $last_sort = M("food_classify")->where($map)->find();
               $last_sort['packageids']= $this->_get_package_relationship_by_sortid($last_sort['id']);
               $last_sort['packagename']=$this->get_name_by_packageid($last_sort['packageids']);
               $last_sort['totalprice']=  $this->get_total_price_by_packageid($last_sort['packageids']);
               $last_sort['institutionid'] = $institutions[0]['id'];
               $last_sort['institutionname'] = $institutions[0]['name'];

               $this->assign('last_sort', $last_sort);
               $this->assign('isnew', $isnew);
               
            }
            else
            {
                $this->assign('isnew', $isnew);
            }
            
            
            

            
            
            $this->display(); 
        }
    }
    
    /*
     * 插入图片到fd_fundings_image表
     */
    private function insert_image($img_url)
    {
        $DB = M("fundings_image");
        $data['img_url']=$img_url;
        
        $id = $DB->add($data);
        
        return $id;
        
    }


    /*
     * 检测项目选择
     */
    public function publish_package_list() {
        /*
         * 过滤项目对应的产品的分类
         * 前期木有，全场通用
         */
        $DB = M('fundings_package');
//        $map
        $res = $DB->where($map)->select();

        foreach ($res as $key => $value) {
            //增加项目的名字
            $res[$key]['price']=$value['price']*0.01;
        }
        
        
        
       
        
        $this->assign('result', $res);
//        print_r($res);
        
        $this->display();
    }
    
    /*
     * publish_package_detail
     */
    public function publish_package_detail() {
        $id = I('get.id');
        $DB = M('fundings_package');
        
        $res = $DB->find($id);
        
        $this->assign('package', $res);
        $this->display();
        
    }
    
    /*
     * 检测机构选择
     */
    public function publish_institution_list() {
         /*
         * 过滤项目对应的产品的分类
         * 前期木有，全场通用
         */
        $DB = M('institution');
//        $map
        $res = $DB->where($map)->select();
        
        $this->assign('result', $res);
        
        $this->display();
    }
    
    
    /*
     * 产品分类选择
     */
    public function publish_sorts_list() {
        $DB = M("food_classify");
        $map['pid']=0;  //获取大类
        
        $res = $DB->where($map)->select();
        /*
         * 获取该分类下的管理检测内容
         */
        foreach ($res as $key => $value) {
            $res[$key]['packageids']= $this->_get_package_relationship_by_sortid($value['id']);
            $res[$key]['packagename']=$this->get_name_by_packageid($res[$key]['packageids']);
            $res[$key]['totalprice']=  $this->get_total_price_by_packageid($res[$key]['packageids']);
        }
        
        $this->assign('sorts', $res);
        
//        print_r($res);
//        exit();
        $this->display();
    }
    
    public function publish_pay_money() {
         $fdid=I('get.fdid');
//         找出项目资料
         $res = M("fundings")->find($fdid);
         $this->assign('fd_info', $res);
         
         $founding_username  = M("members")->where(array('id'=>$res['mid']))->getField("username");
         $this->assign('founding_username', $founding_username);
         
         $this->assign('fdid', $fdid);
         $this->display();
    }
    
    
    public function publish_money_confirm() {
        $fdid=I('post.fdid');
        $donate = I('post.donate_money');
        
        /*
         * 找出当前用户的openid
         */
        $member = session('member');
        $openid = $member['wxopenid'];
        
        
        /*
         * 找出项目的资料
         */
        $fd_info = M("fundings")->find($fdid);
        /*
         * 生成红包参数资料
         */
        $random_code = $this->_create_redpack_param($fdid, $openid);
        $this->assign('random_code', $random_code);
        
        /*
        * 生成临时支付的订单
        */
       $DB_sponsor = M('fundings_sponsor');
       $data_sponsor['mid']=$member['id'];
       $data_sponsor['paytype']=1;
       $data_sponsor['paytime']=I('server.REQUEST_TIME');
       $data_sponsor['money']=$donate*100;
       $data_sponsor['fid']=$fdid;
       $data_sponsor['status']=0;
       $data_sponsor['type']=0;

       $sponsor_id = $DB_sponsor->add($data_sponsor);
        
        
        //微信支付初始化
//        $wechat = new \Com\WechatAuth(C('appid'),C('appsecret'));
//        $test = new \Org\Net\Http();
        $jsApi = new \Com\WxPayPubHelper\JsApi_pub();
        $WxPayConf_pub = new \Com\WxPayPubHelper\WxPayConf_pub();
//        if (!isset($_GET['code']))
//	{
//		//触发微信返回code码
//		$url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL);
//		Header("Location: $url"); 
//	}else
//	{
//		//获取code码，以获取openid
//	    $code = $_GET['code'];
//		$jsApi->setCode($code);
//		$openid = $jsApi->getOpenId();
//	}
        
        
        //=========步骤2：使用统一支付接口，获取prepay_id============
	//使用统一支付接口
//        echo "3";
	$unifiedOrder = new \Com\WxPayPubHelper\UnifiedOrder_pub();
//	echo $order['ordernum'];
        //设置统一支付接口参数
	//设置必填参数
	//appid已填,商户无需重复填写
	//mch_id已填,商户无需重复填写
	//noncestr已填,商户无需重复填写
	//spbill_create_ip已填,商户无需重复填写
	//sign已填,商户无需重复填写
	$unifiedOrder->setParameter("openid","$openid");//商品描述
	$unifiedOrder->setParameter("body",$fd_info['pjname']);//商品描述
	//自定义订单号，此处仅作举例
//	$timeStamp = I('server.REQUEST_TIME');
//	$out_trade_no = WxPayConf_pub::APPID."$timeStamp";
	$unifiedOrder->setParameter("out_trade_no",$sponsor_id."|".I('server.REQUEST_TIME'));//商户订单号 
        //判断环境
        if(!C('debug'))
        {
//            $unifiedOrder->setParameter("total_fee",1);//总金额
//            $unifiedOrder->setParameter("total_fee",($donate)*100);//总金额
            if($openid=="ozaQJv7aFKV0yIy4jybu9FqEo6XY")
            {
                $unifiedOrder->setParameter("total_fee",1);//总金额
            }
            else
            {
//                $unifiedOrder->setParameter("total_fee",1);//总金额
                $unifiedOrder->setParameter("total_fee",($donate)*100);//总金额
            }
        }
        else
        {
            $unifiedOrder->setParameter("total_fee",1);//总金额
        }
	
//        $unifiedOrder->setParameter("total_fee",1);//总金额
	$unifiedOrder->setParameter("notify_url",$WxPayConf_pub::NOTIFY_URL);//通知地址 
	$unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
	//非必填参数，商户可根据实际情况选填
	//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号  
	//$unifiedOrder->setParameter("device_info","XXXX");//设备号 
	//$unifiedOrder->setParameter("attach","XXXX");//附加数据 
	//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
	//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 
	$unifiedOrder->setParameter("goods_tag",I('server.REQUEST_TIME'));//商品标记 
	//$unifiedOrder->setParameter("openid","XXXX");//用户标识
	$unifiedOrder->setParameter("product_id",$fd_info['id']);//商品ID

	$prepay_id = $unifiedOrder->getPrepayId();
	//=========步骤3：使用jsapi调起支付============
	$jsApi->setPrepayId($prepay_id);

	$jsApiParameters = $jsApi->getParameters();
	//echo $jsApiParameters;
        
        $this->assign('jsApiParameters', $jsApiParameters);
//        print_r($jsApiParameters);
//        die();
        $this->assign('fd_info', $fd_info);
        $this->assign('donatemoney', $donate);
        $this->display();
    }
    
    
    /*
     * 给号钱之后要分享
     */
    public function publish_ok_to_share() {
        $fdid = I('get.fdid');
        if(empty($fdid))
        {
            redirect(U('M/Index/index'));
        }
        /*
         * 找出项目的资料
         */
        $fd_info = M("fundings")->find($fdid);
        if(empty($fd_info))
        {
            redirect(U('M/Index/index'));
        }
        
        
        $this->assign('fd_info', $fd_info);
        $this->display();
    }
    
    
    
    
    /*
     * 列举项目列表
     */
    public function lists() {
        
        //获取项目的列表信息
        $state = I('get.state');
        switch ($state) {
            case 1:
                $this->assign("sub_title",'众测项目' );

                break;
            case 2:
                $this->assign("sub_title",'抽样中的项目');

                break;

            default:
                $this->assign("sub_title",'最新报告');
                break;
        }
        $DB = M('fundings');
        
        $map['state']=$state;
        
        /*
         * 临时处理
         * 
         * 后面增加一个utime
         * 更新报告去更新 utime
         * 
         */
        $res = $DB->where($map)->order("ctime DESC")->select();
        
        foreach ($res as $key => $value) {
            $res[$key]['institution'] = $this->get_name_by_institutionid($value['institutionid']);
            $res[$key]['packagename']=  $this->get_name_by_packageid($value['packageid']);
            if(mb_strlen($res[$key]['packagename'],"utf-8")>10)
            {
                $res[$key]['packagename'] = mb_substr($res[$key]['packagename'], 0,8,'utf-8')."...";
                
            }
            $res[$key]['rate'] = round($value['finish']*100/($value['emoney']+$value['smoney']*$value['samnum']),0);
            if($res[$key]['rate']==0 && ($value['finish']>0))
            {
                $res[$key]['rate']=1;
            }
            
            if($res[$key]['rate']>99 &&($value['finish']<($value['emoney']+$value['smoney']*$value['samnum'])))
            {
                $res[$key]['rate']=99;
            }
            
            $res[$key]['show_mark_icon']=  $this->_get_fouding_list_mark(0,$value['result'],$value['state']);
            //目标金额
            $res[$key]['finish_money']=$value['finish']/100;
            $res[$key]['target_money']= ($value['emoney']+$value['smoney']*$value['samnum'])/100;
            /*
            * 获取支持的人数
            */
            $res[$key]['sponsor_count']=  $this->_get_founding_sponsor_count($value['id']);
            
            /*
             * 获取发起人的资料
             */
            $res[$key]['founder'] = $this->_get_member_info($value['mid']);
            
            if(strlen($res[$key]['batch'])>12)
            {
                $res[$key]['batch']= substr($res[$key]['batch'], 0,12)."...";
            }
            
            $res[$key]['qualified']=$value['result'];
            $res[$key]['testing_result']=$this->_get_testing_report_short_analyze($value['testreportid']);
        }
        
        
        
        

        $this->assign('fundings', $res);
        $this->assign("state", $state);
        switch ($state) {
            case 1:
                $this->display('founding_1_lists');

                break;
            case 2:
                $this->display();

                break;
            case 3:
                $this->display('founding_3_lists');

                break;

            default:
                $this->display();
                break;
        }
        
    }
    
     /*
     * 获取报告的列表显示的不合格分析
     */
    public function _get_testing_report_short_analyze($id) {
        if(empty($id))
        {
            return "";
        }
        else
        {
            $DB = M("testreport");
            $res = $DB->find($id);
            if(empty($res))
            {
                return "";
            }
            else
            {
                return $res['content'];
            }
            
        }
        
    }
    
    
    
    /*
     * 项目确认支付页面
     */
    public function donate_money_confirm() {
        /*
         * Date: 2015-12-15
         * 增加一个判断是否是专题来源
         * 
         */
//        print_r($_POST);
//        exit();
        $specialid = trim(I("post.specialid"));
        
        if(empty($specialid))
        {
            $specialid=0;
        }
        
        $this->assign("specialid", $specialid);
        /*
         * 增加一个判断是否是专题来源 end
         */
        
        $fdid=I('post.fdid');
//        exit($fdid);
        $donate = I('post.donate_money');
        
        $mid = session("mid"); 
        
        $rp_id = I("post.rp_id");
        if(empty($rp_id)||$rp_id==0)
        {
             $data_sponsor['rp_id']=0;
             $data_sponsor['status']=0;
        }
        else
        {
            //找出来红包的对应金额
            $res_redpack =  M("redpack_create_records")->find($rp_id);
            if($donate>=$res_redpackp['cash'])
            {
                $donate -=$res_redpackp['cash'];
                $data_sponsor['status']=0;
            }
            else
            {
                $donate=0;
                $data_sponsor['status']=1;
            }
            
            $data_sponsor['rp_id']=$rp_id;
        }
        
        /*
        * 生成临时支付的订单
        */
       $DB_sponsor = M('fundings_sponsor');
       $data_sponsor['mid']=$mid;
       $data_sponsor['paytype']=1; //1 代表微信支付， 2支付宝，3 银联
       $data_sponsor['paytime']=I('server.REQUEST_TIME');
       $data_sponsor['money']=$donate*100;
       $data_sponsor['fid']=$fdid;
       
       $data_sponsor['type']=0;

       $sponsor_id = $DB_sponsor->add($data_sponsor);
       
       
        
        /*
         * 找出当前用户的openid
         */
        $member = session('member');
        $openid = $member['wxopenid'];
        
        
        /*
         * 找出项目的资料
         */
        $fd_info = M("fundings")->find($fdid);
        
        
        /*
         * 生成红包参数资料
         */
        $random_code = $this->_create_redpack_param($fdid, $openid);
        
        if($donate==0)
       {
//           无需支付，直接跳转到成功支付的界面
            /*
            * 更新这个记录到众筹的项目的总金额去
            */
           $this->_founding_finish_money_increase($fdid, I('post.donate_money'));

           /*
            * 判断founding 是否满标，满的话，就改状态
            */
           $this->_chk_if_donate_ok($fdid);

           /*
            * 增加用户的健康豆
            */
           $this->member_action_bonus('payment', $mid, I('post.donate_money')/100);


           /*
            * 更新用户使用的红包
            */
           if($rp_id!=0)
           {
               $this->_update_redpack_status($rp_id);
           }
           
           
           
            redirect(U('M/Founding/detail_new_after_payment',array('fdid'=>$fdid,'random_code'=>$random_code)));
       }
       
        
//        print_r($random_code);
//        exit();
        
        $this->assign('random_code', $random_code);
        
        
        
        
        //微信支付初始化
//        $wechat = new \Com\WechatAuth(C('appid'),C('appsecret'));
//        $test = new \Org\Net\Http();
        $jsApi = new \Com\WxPayPubHelper\JsApi_pub();
        $WxPayConf_pub = new \Com\WxPayPubHelper\WxPayConf_pub();
//        if (!isset($_GET['code']))
//	{
//		//触发微信返回code码
//		$url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL);
//		Header("Location: $url"); 
//	}else
//	{
//		//获取code码，以获取openid
//	    $code = $_GET['code'];
//		$jsApi->setCode($code);
//		$openid = $jsApi->getOpenId();
//	}
        
        
        //=========步骤2：使用统一支付接口，获取prepay_id============
	//使用统一支付接口
//        echo "3";
	$unifiedOrder = new \Com\WxPayPubHelper\UnifiedOrder_pub();
//	echo $order['ordernum'];
        //设置统一支付接口参数
	//设置必填参数
	//appid已填,商户无需重复填写
	//mch_id已填,商户无需重复填写
	//noncestr已填,商户无需重复填写
	//spbill_create_ip已填,商户无需重复填写
	//sign已填,商户无需重复填写
	$unifiedOrder->setParameter("openid","$openid");//商品描述
	$unifiedOrder->setParameter("body",$fd_info['pjname']);//商品描述
	//自定义订单号，此处仅作举例
//	$timeStamp = I('server.REQUEST_TIME');
//	$out_trade_no = WxPayConf_pub::APPID."$timeStamp";
	$unifiedOrder->setParameter("out_trade_no",$sponsor_id."|".I('server.REQUEST_TIME'));//商户订单号 
//	$unifiedOrder->setParameter("total_fee",($donate)*100);//总金额
//        $unifiedOrder->setParameter("total_fee",1);//总金额
        //判断环境
        if(!C('debug'))
        {
            if($openid=="ozaQJv7aFKV0yIy4jybu9FqEo6XY")
            {
                $unifiedOrder->setParameter("total_fee",1);//总金额
            }
            else
            {
//                $unifiedOrder->setParameter("total_fee",1);//总金额
                $unifiedOrder->setParameter("total_fee",($donate)*100);//总金额
            }
            
        }
        else
        {
            $unifiedOrder->setParameter("total_fee",1);//总金额
        }
        
        
	$unifiedOrder->setParameter("notify_url",$WxPayConf_pub::NOTIFY_URL);//通知地址 
	$unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
	//非必填参数，商户可根据实际情况选填
	//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号  
	//$unifiedOrder->setParameter("device_info","XXXX");//设备号 
	$unifiedOrder->setParameter("attach","$sponsor_id");//附加数据 
	//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
	//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 
	$unifiedOrder->setParameter("goods_tag",I('server.REQUEST_TIME'));//商品标记 
	//$unifiedOrder->setParameter("openid","XXXX");//用户标识
	$unifiedOrder->setParameter("product_id",$fd_info['id']);//商品ID

	$prepay_id = $unifiedOrder->getPrepayId();
	//=========步骤3：使用jsapi调起支付============
	$jsApi->setPrepayId($prepay_id);

	$jsApiParameters = $jsApi->getParameters();
	//echo $jsApiParameters;
        
        $this->assign('jsApiParameters', $jsApiParameters);
        
//        print_r($jsApiParameters);
        $this->assign('fd_info', $fd_info);
        $this->assign('donatemoney', $donate);
        if($specialid>0)
        {
            $this->display("donate_money_confirm_for_special");
        }
        else
        {
            $this->display();
        }
        
    }
    
    /*
     * 项目跟投选择金额
     */
    public function donate_pay_money() {
        /*
         * Date: 2015-12-15
         * 增加一个判断是否是专题来源
         * 
         */
        $specialid = trim(I("get.specialid"));
        
        if(empty($specialid))
        {
            $specialid=0;
        }
        
        $this->assign("specialid", $specialid);
        /*
         * 增加一个判断是否是专题来源 end
         */
        
        
        $fdid=I('get.fdid');
        $this->assign("fdid", $fdid);
        
        //         找出项目资料
         $res = M("fundings")->find($fdid);
         $this->assign('fd_info', $res);
         
         $founding_username  = M("members")->where(array('id'=>$res['mid']))->getField("username");
         $this->assign('founding_username', $founding_username);
         
         
         /*
          * 获取红包的剩余个数
          */
         //可用的红包数目
        $DB_redpack_receive_records =M("redpack_receive_records");
        $map['mid']=session("mid");
        $map['is_used']=0;
        $map['fd_redpack_receive_records.etime']=array('gt',I("server.REQUEST_TIME"));

        $redpack_res = $DB_redpack_receive_records->where($map)->join("LEFT JOIN fd_redpack_create_records ON fd_redpack_create_records.id = fd_redpack_receive_records.rp_id")->order('cash,ctime ASC')->getField('fd_redpack_receive_records.id as id,fd_redpack_receive_records.mid as mid,fd_redpack_receive_records.openid as openid,fd_redpack_receive_records.rp_id as rp_id,fd_redpack_receive_records.is_used as is_used,fd_redpack_receive_records.ctime as ctime,fd_redpack_receive_records.etime as etime,fd_redpack_receive_records.fid as fid,fd_redpack_create_records.random_code as random_code,fd_redpack_create_records.redpack_code as redpack_code,fd_redpack_create_records.cash as cash,fd_redpack_create_records.isactived as isactived,fd_redpack_create_records.slogan as slogan');

//                
//        $DB_redpack_receive_records =M("redpack_receive_records");
//        $map['mid']=session("mid");
////        print_r($map);
//        $map['is_used']=0;
//        $map['fd_redpack_receive_records.etime']=array('gt',I("server.REQUEST_TIME"));
//        
//        
//        
//        $redpack_res = $DB_redpack_receive_records->where($map)->order('')->select();
        
        $redpack_count = count($redpack_res);
        
        if($redpack_count>0)
        {
            $redpack_res = (array_values($redpack_res));
            $redpack_one = $redpack_res[0];
        }
        
        $this->assign("redpack_one", $redpack_one);
        
//        print_r($redpack_one);
        
        
        
        
        $this->assign("redpack_count", $redpack_count);
        
        $this->display();
    }
    
    /*
     * 进去选择红包的功能
     */
    public function payment_redpack_choose() {
        $DB_redpack_receive_records =M("redpack_receive_records");
        $map['mid']=session("mid");
        $map['is_used']=0;
        $map['fd_redpack_receive_records.etime']=array('gt',I("server.REQUEST_TIME"));

        $redpack_res = $DB_redpack_receive_records->where($map)->join("LEFT JOIN fd_redpack_create_records ON fd_redpack_create_records.id = fd_redpack_receive_records.rp_id")->order('cash,ctime ASC')->getField('fd_redpack_receive_records.id as id,fd_redpack_receive_records.mid as mid,fd_redpack_receive_records.openid as openid,fd_redpack_receive_records.rp_id as rp_id,fd_redpack_receive_records.is_used as is_used,fd_redpack_receive_records.ctime as ctime,fd_redpack_receive_records.etime as etime,fd_redpack_receive_records.fid as fid,fd_redpack_create_records.random_code as random_code,fd_redpack_create_records.redpack_code as redpack_code,fd_redpack_create_records.cash as cash,fd_redpack_create_records.isactived as isactived,fd_redpack_create_records.slogan as slogan');
        
        foreach ($redpack_res as $key => $value) {
            $redpack_res[$key]['cash'] = (int)$value['cash'];
        }
        $this->assign("redpack_res", $redpack_res);
        $this->display();
    }
    
    /*
     * 给好钱之后要分享
     */
    public function donate_ok_to_share() {
        $fdid = I('get.fdid');
        if(empty($fdid))
        {
            redirect(U('M/Index/index'));
        }
        /*
         * 找出项目的资料
         */
        $fd_info = M("fundings")->find($fdid);
        if(empty($fd_info))
        {
            redirect(U('M/Index/index'));
        }
        
        
        $this->assign('fd_info', $fd_info);
        $this->display();
    }
    
    /*
     * 专题的给钱后分享页面
     */
    public function donate_ok_to_share_for_special() {
        /*
         * Date: 2015-12-15
         * 增加一个判断是否是专题来源
         * 
         */
        $specialid = trim(I("get.specialid"));
        
        if(empty($specialid))
        {
            $specialid=0;
        }
        
        $this->assign("specialid", $specialid);
        /*
         * 增加一个判断是否是专题来源 end
         */
        
        $fdid = I('get.fdid');
        if(empty($fdid))
        {
            redirect(U('M/Index/index'));
        }
        /*
         * 找出项目的资料
         */
        $fd_info = M("fundings")->find($fdid);
        if(empty($fd_info))
        {
            redirect(U('M/Index/index'));
        }
        
        
        $this->assign('fd_info', $fd_info);
        $this->display();
    }
    
    
    /*
     * 支付确认页面
     */
    
    public function wx_app_pay_notify() {
        
       $notify = new \Com\WxPay\Notify_pub();
       //使用通用通知接口
//	$notify = new Notify_pub();

	//存储微信的回调
	$xml = $GLOBALS['HTTP_RAW_POST_DATA'];	
	$notify->saveData($xml);
        
        //存入本地
        $data['ordernum']=$notify->data['out_trade_no'];
        $data['return_code'] = $notify->data["return_code"];
        $data['content']=json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $data['ctime']= I('server.REQUEST_TIME');
        M('wx_pay_log')->add($data);
	
	//验证签名，并回应微信。
	//对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
	//微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
	//尽可能提高通知的成功率，但微信不保证通知最终能成功。
	if($notify->checkSign() == FALSE){
		$notify->setReturnParameter("return_code","FAIL");//返回状态码
		$notify->setReturnParameter("return_msg","签名失败");//返回信息
	}else{
		$notify->setReturnParameter("return_code","SUCCESS");//设置返回码
	}
	$returnXml = $notify->returnXml();
	echo $returnXml;
	
	//==商户根据实际情况设置相应的处理流程，此处仅作举例=======
	
//	//以log文件形式记录回调信息
//	$log_ = new Log_();
//	$log_name="./notify_url.log";//log文件路径
//	$log_->log_result($log_name,"【接收到的notify通知】:\n".$xml."\n");

	if($notify->checkSign() == TRUE)
	{
		if ($notify->data["return_code"] == "FAIL") {
			//此处应该更新一下订单状态，商户自行增删操作
//			$log_->log_result($log_name,"【通信出错】:\n".$xml."\n");
		}
		elseif($notify->data["result_code"] == "FAIL"){
			//此处应该更新一下订单状态，商户自行增删操作
//			$log_->log_result($log_name,"【业务出错】:\n".$xml."\n");
		}
		else{
                    //此处应该更新一下订单状态，商户自行增删操作
                    
//                        $ordernum = $notify->data['out_trade_no'];
//                        $ordernum = substr($ordernum, 0,19);
                        $DB = M('fundings_sponsor');
                        $orderid = $notify->data['out_trade_no'];
                        $orderid_array = explode('|', $orderid);
                        array_pop($orderid_array); //去掉最后的时间戳
                        $map_order['id']=array('in',$orderid_array);
                        $results = $DB->where($map_order)->select();
                        if(!empty($results))
                        {
                            foreach ($results as $key => $value) {
                                /*
                                 * 判断该订单的状态，如果是已经为1的就不用处理了
                                 * 
                                 */
//                                $order = $DB->find($value['id']);
                                if($value['status']!=1)
                                {
//                                    $id = $value['id'];
                                    $DB->id = $value['id'];
                                    $DB->status=1;
                                    $DB->paytype = 1; //支付方式，0 未知（包含当面支付），1是微信，2 支付宝，3银联
                                    $DB->save();
                                    
                                    
                                    /*
                                     * 更新这个记录到众筹的项目的总金额去
                                     */
                                    $this->_founding_finish_money_increase($value['fid'], $value['money']);
                                    
                                    /*
                                     * 判断founding 是否满标，满的话，就改状态
                                     */
                                    $this->_chk_if_donate_ok($value['fid']);
                                    
                                    /*
                                     * 增加用户的健康豆
                                     */
                                    $this->member_action_bonus('payment', $value['mid'], $value['money']/100);
                                    
                                    
                                    /*
                                     * 更新用户使用的红包
                                     */
                                    if($value['rp_id']!=0)
                                    {
                                        $this->_update_redpack_status($value['rp_id']);
                                    }
 
                                }
                                
                                
                                
                            }
                        }

	}
    }
    }
    
    /*
     * 微信支付确认页面
     */
    public function wxpay_notify() {
        
       $notify = new \Com\WxPayPubHelper\Notify_pub();
       //使用通用通知接口
//	$notify = new Notify_pub();

	//存储微信的回调
	$xml = $GLOBALS['HTTP_RAW_POST_DATA'];	
	$notify->saveData($xml);
        
        //存入本地
        $data['ordernum']=$notify->data['out_trade_no'];
        $data['return_code'] = $notify->data["return_code"];
        $data['content']=json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $data['ctime']= I('server.REQUEST_TIME');
        M('wx_pay_log')->add($data);
	
	//验证签名，并回应微信。
	//对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
	//微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
	//尽可能提高通知的成功率，但微信不保证通知最终能成功。
	if($notify->checkSign() == FALSE){
		$notify->setReturnParameter("return_code","FAIL");//返回状态码
		$notify->setReturnParameter("return_msg","签名失败");//返回信息
	}else{
		$notify->setReturnParameter("return_code","SUCCESS");//设置返回码
	}
	$returnXml = $notify->returnXml();
	echo $returnXml;
	
	//==商户根据实际情况设置相应的处理流程，此处仅作举例=======
	
//	//以log文件形式记录回调信息
//	$log_ = new Log_();
//	$log_name="./notify_url.log";//log文件路径
//	$log_->log_result($log_name,"【接收到的notify通知】:\n".$xml."\n");

	if($notify->checkSign() == TRUE)
	{
		if ($notify->data["return_code"] == "FAIL") {
			//此处应该更新一下订单状态，商户自行增删操作
//			$log_->log_result($log_name,"【通信出错】:\n".$xml."\n");
		}
		elseif($notify->data["result_code"] == "FAIL"){
			//此处应该更新一下订单状态，商户自行增删操作
//			$log_->log_result($log_name,"【业务出错】:\n".$xml."\n");
		}
		else{
            //此处应该更新一下订单状态，商户自行增删操作
            
    //                        $ordernum = $notify->data['out_trade_no'];
    //                        $ordernum = substr($ordernum, 0,19);
                $DB = M('fundings_sponsor');
                $orderid = $notify->data['out_trade_no'];
                $orderid_array = explode('|', $orderid);
                array_pop($orderid_array); //去掉最后的时间戳
                $map_order['id']=array('in',$orderid_array);
                $results = $DB->where($map_order)->select();
                if(!empty($results))
                {
                    foreach ($results as $key => $value) {
                        /*
                         * 判断该订单的状态，如果是已经为1的就不用处理了
                         * 
                         */
    //                                $order = $DB->find($value['id']);
                        if($value['status']!=1)
                        {
    //                                    $id = $value['id'];
                            $DB->id = $value['id'];
                            $DB->status=1;
                            $DB->paytype = 1; //支付方式，0 未知（包含当面支付），1是微信，2 支付宝，3银联
                            $DB->save();
                            
                            /*
                             * 更新这个记录到众筹的项目的总金额去
                             */
                            $this->_founding_finish_money_increase($value['fid'], $value['money']);
                            
                            /*
                             * 判断founding 是否满标，满的话，就改状态
                             */
                            $this->_chk_if_donate_ok($value['fid']);
                            
                            /*
                            * 增加用户的健康豆
                            */
                           $this->member_action_bonus('payment', $value['mid'], $value['money']/100);
                           
                           /*
                            * 更新用户使用的红包
                            */
                           if($value['rp_id']!=0)
                           {
                               $this->_update_redpack_status($value['rp_id']);
                           }

                        }
                        
                    }
                }
                        

	}
    }
    }
    
    
    /*
     * 更新用户的红包状态
     */
    private function _update_redpack_status($rp_id) {
        $DB_redpack_receive_records = M("redpack_receive_records");
        $map['rp_id']=$rp_id;
        
        $res_redpack_receive_records = $DB_redpack_receive_records->where($map)->find();
        
        if(!empty($res_redpack_receive_records))
        {
            $DB_redpack_receive_records->id = $res_redpack_receive_records['id'];
            $DB_redpack_receive_records->is_used = 1;
            $DB_redpack_receive_records->save();
        }
        
    }




    /*
     * 检测机构查看
     */
    public function publish_institution_detail() {
        $id = I('get.id');
        $res  = M("institution")->find($id);
        
        $this->assign("result", $res);
        $this->display();
    }
    
    /*
     * 查看项目的支持者
     */
    public function sponsors() {
        $fdid = I('get.fdid');
        
        $map['status']=1;
        $map['fid']=$fdid;
        
        $DB = M("fundings_sponsor");
        
        $res = $DB->where($map)->order("paytime DESC")->select();
        
        if(!empty($res))
        {
            /*
            * 根据mid 获取到 头像等信息
            */
           foreach ($res as $key => $value) {
               /*
               * 获取单个用户的头像信息
               */
               $res[$key]['avatar']=  $this->_get_one_avatar($value['mid']);
               $res[$key]['username']=  $this->_get_member_nickname($value['mid']);
               $res[$key]['money']=  $value['money']/100;
           }
        }
        else
        {
            $res = "";
        }
        
        
        $this->assign('sponsors', $res);
        $this->assign('fdid', $fdid);
        
        $this->display();
    }
    
    /*
     * 
     * 项目的评论列表
     * 
     */
    public function comments() {
        $fdid = I('get.fdid');
        $pid = I('get.pid');
        
        $map['pid']=$pid;
        $map['ctype']=1;
        $map['for_id']=$fdid;
        $map['ishidden']=0;
        
        $DB = M("comments");
        $res = $DB->where($map)->order("ctime DESC")->select();
        
        foreach ($res as $key => $value) {
            $res[$key]['username']=$this->_get_member_nickname($value['mid']);
            $res[$key]['avatar']=  $this->_get_one_avatar($value['mid']);
        }
        
        $this->assign('result', $res);
        $this->assign('mid', session("mid"));
        $this->assign('fdid', $fdid);
        
        $this->display();
        
        
    }
    
    /*
     * 查看评论的评论
     */
    public function comment_detail() {
        $fdid = I('get.fdid');
        $pid = I('get.pid');
        $DB = M("comments");
        //父评论信息
        $pcomment = $DB->find($pid);
        $pcomment['username']=$this->_get_member_nickname($pcomment['mid']);
        $pcomment['avatar']=  $this->_get_one_avatar($pcomment['mid']);
        
        //众多的子评论信息
        $map['pid']=$pid;
        $map['ctype']=1;
        $map['for_id']=$fdid;
        $map['ishidden']=0;
        
        
        $res = $DB->where($map)->order("ctime DESC")->select();
        foreach ($res as $key => $value) {
            $res[$key]['username']=$this->_get_member_nickname($value['mid']);
            $res[$key]['avatar']=  $this->_get_one_avatar($value['mid']);
        }
        
        $this->assign('pcomment', $pcomment);
        $this->assign('result', $res);
        $this->assign('mid', session('mid'));
//        print_r(session('mid'));
        $this->assign('fdid', $fdid);
        $this->assign('pid', $pid);
        
        $this->display();
    }

    
    /*
     * 
     * 项目的评论添加
     * 调用widget 里边的函数
     * 
     */
    public function comments_add() {
        //        comment_add($pid=0,$mid=0,$content="",$ctype=0,$for_id=0)
        $pid = I('post.pid');
        $mid = I('post.mid');
        $content = I("post.content");
        $for_id = I("post.fdid");
        
        $chk_back = chk_bad_words($content,1);
        if($chk_back){

            echo json_encode(2);
        }else{

          $res = R("Widget/comment_add",array('pid'=>$pid,'mid'=>$mid,'content'=>"$content",'ctype'=>1,'for_id'=>$for_id));
        
          if($res)
          {
              /*
              * 增加用户的健康豆
              */
             $this->member_action_bonus('comment', $mid, 1);
              echo 1;
          }
          else
          {
              echo 0;
          }
        }
    }
    
    /*
     * 
     * 项目的评论点赞
     * 
     */
    public function comments_like_add() {
        $mid = I('get.mid');

        if($mid)
        {
            $cid = I("get.cid");


            $data['cid']=$cid;
            $data['mid']=$mid;
            $data['ctime']=I("server.REQUEST_TIME");
            
            $DB = M("comment_likes");
            
            $id = $DB->add($data);
            
            if($id)
            {
                $DB_comment = M("comments");
                $DB_comment->where("id=".$cid)->setInc("likecount");
//                print_r($DB_comment->getLastSql());
                
                echo 1;
            }
        }
        else
        {
            echo 0;
        }
    }
    
    /*
     * 针对项目的收藏功能
     */
    
    public function add_one_colletion() {
       /*
        * 收藏or 取消收藏
        * 0 取消收藏
        * 1 收藏
        * 
        * ctype 1 项目, 2 资讯，
        */
        $mid = I('get.mid');
        
        if($mid)
        {
            $ctype = 1;
            $forid = I("get.id");
            
            $ifcollection = I("get.ifcollection");
            
            $DB = M("collections");
       
            if($ifcollection==1)
            {
                $map['ctype']=$ctype;
                $map['for_id']=$forid;
                $map['mid']=$mid;

                $DB->where($map)->delete();
                
                 echo 1;
            }
            else
            {
                //新增
                $data['ctype']=$ctype;
                $data['for_id']=$forid;
                $data['mid']=$mid;
                $data['ctime']=I("server.REQUEST_TIME");


                $id =$DB->add($data,array(),true);
                if($id)
                {
                     echo 1;
                }

            }
           
        }
        else
        {
            echo 0;
        }
        
        
       
   }
    
    
    
    
    
    
    
    /*
     * 不安全的食品列表
     */
    public function unsafe() {
        
//        $DB_search_tags = M('search_tags');
//        $maps['type'] = 1;
//        $tag_list = $DB_search_tags->where($maps)->order("rank DESC")->select();
//        $this->assign('tag_list',$tag_list);

        $DB = M('fundings');
        $map['state']=3;
        $map['result']=2;
        
        $res = $DB->where($map)->order("state DESC,result DESC")->select();
        
//        print_r($res);
//        exit();
        foreach ($res as $key => $value) {
            $res[$key]['name']= $value['pjname'];
            $res[$key]['isurl']= 0;
            $res[$key]['url']= "";
            $res[$key]['qualified']= 0;
            $res[$key]['show_mark_icon']=  $this->_get_fouding_list_mark(0,$value['result'],$value['state']);
            $res[$key]['location']= $value['location'];
            $res[$key]['testing_date']= date("Y-m-d",$value['ctime']);
            $res[$key]['batch_number']= $value['batch'];
            
            $testing_result = $this->_get_testing_report_short_analyze($value['testreportid']);

                if(!empty($testing_result)){

                    $res[$key]['testing_result'] = $testing_result.'';
                }else{

                    $res[$key]['testing_result'] = '';
                }
            
        }
        
        $count_res = count($res);
        
        //找出关键字相关的记录
            $res_thirdparty = $this->get_thirdparty_product_by_name_for_unsafe_index(0,10);
            
            if(!empty($res_thirdparty))
            {
                foreach ($res_thirdparty as $key => $value) {
                    
//                    $res[$count_res+$key]['pinfo']=  $this->get_third_party_info_by_id($value['id']);
                    
                    $res[$count_res+$key]['name'] = $value['product_name'];
                    $res[$count_res+$key]['id'] = 0;
                    $res[$count_res+$key]['isurl']= 1;
                    $res[$count_res+$key]['url']= C('product_domain').U('M/Founding/show_thirdparty_data',array('id'=>$value['id']));
                    $res[$count_res+$key]['qualified']= $value['qualified'];
                    $res[$count_res+$key]['show_mark_icon']=  $this->_get_fouding_list_mark(1,$value['qualified'],3);
                    $res[$count_res+$key]['location']= $value['province'];
//                    $res[$count_res+$key]['testing_date']= $value['notification_number'];
                    $res[$count_res+$key]['batch_number']= $value['cdate'];
                    
                    if($value['qualified']==0)
                    {
                        
                        if(!empty($value['items']))
                        {
                            $res[$count_res+$key]['testing_result']= $value['items']." 超标 ";
                        }
                        else
                        {
                            $res[$count_res+$key]['testing_result']="";
                        }
                    }
                    else
                    {
                        $res[$count_res+$key]['testing_result']="";
                    }
                }
            }
            $this->assign('results', $res);
            
            
        $this->display();   
    }
    
    /*
     * 曝光台产品
     */
    public function unsafe_list() {
        $keywords = I('get.keywords');
        
        $DB = M('fundings');
        $map['pdname']=array('like',"%$keywords%");
        $map['state']=3;
        $map['result']=2;
        
        $res = $DB->where($map)->order("state DESC,result DESC")->select();
        
//        print_r($res);
//        exit();
        foreach ($res as $key => $value) {
            $res[$key]['name']= $value['pjname'];
            $res[$key]['isurl']= 0;
            $res[$key]['url']= "";
            $res[$key]['qualified']= 0;
            $res[$key]['show_mark_icon']=  $this->_get_fouding_list_mark(0,$value['result'],$value['state']);
            $res[$key]['location']= $value['location'];
            $res[$key]['testing_date']= date("Y-m-d",$value['ctime']);
            $res[$key]['batch_number']= $value['batch'];
            
            $testing_result = $this->_get_testing_report_short_analyze($value['testreportid']);

                if(!empty($testing_result)){

                    $res[$key]['testing_result'] = $testing_result.'';
                }else{

                    $res[$key]['testing_result'] = '';
                }
            
        }
        
        $count_res = count($res);
        
        //找出关键字相关的记录
            $res_thirdparty = $this->get_thirdparty_product_by_name($keywords,0,10);
            
            if(!empty($res_thirdparty))
            {
                foreach ($res_thirdparty as $key => $value) {
                    
                    $res[$count_res+$key]['name'] = $value['product_name'];
                    $res[$count_res+$key]['id'] = 0;
                    $res[$count_res+$key]['isurl']= 1;
                    $res[$count_res+$key]['url']= C('product_domain').U('M/Founding/show_thirdparty_data',array('id'=>$value['id']));
                    $res[$count_res+$key]['qualified']= $value['qualified'];
                    $res[$count_res+$key]['show_mark_icon']=  $this->_get_fouding_list_mark(1,$value['qualified'],3);
                    $res[$count_res+$key]['location']= $value['province'];
//                    $res[$count_res+$key]['testing_date']= $value['notification_number'];
                    $res[$count_res+$key]['batch_number']= $value['cdate'];
                    
                    if($value['qualified']==0)
                    {
                        
                        if(!empty($value['items']))
                        {
                            $res[$count_res+$key]['testing_result']= $value['items']." 超标 ";
                        }
                        else
                        {
                            $res[$count_res+$key]['testing_result']="";
                        }
                    }
                    else
                    {
                        $res[$count_res+$key]['testing_result']="";
                    }
                }
            }
//            print_r($res_thirdparty);
            $this->assign('results', $res);
            $this->assign("keywords", $keywords);
//            print_r($res);
            
            $this->display();
            
    }
    
    /*
     * 曝光台产品分页
     */
    
    public function unsafe_list_by_page() {
        $keywords = I('get.keywords');
        $pagecount = I('get.pagecount');
        
        $startposition = ($pagecount)*10;
        
        $res = array();
        
        $count_res = count($res);
        
        //找出关键字相关的记录
            $res_thirdparty = $this->get_thirdparty_product_by_name($keywords,$startposition,20);
            
            if(!empty($res_thirdparty))
            {
                foreach ($res_thirdparty as $key => $value) {
                    
                    $res[$count_res+$key]['name'] = $value['product_name'];
                    $res[$count_res+$key]['id'] = 0;
                    $res[$count_res+$key]['isurl']= 1;
                    $res[$count_res+$key]['url']= C('product_domain').U('M/Founding/show_thirdparty_data',array('id'=>$value['id']));
                    $res[$count_res+$key]['qualified']= $value['qualified'];
                    $res[$count_res+$key]['show_mark_icon']=  $this->_get_fouding_list_mark(1,$value['qualified'],3);
                    $res[$count_res+$key]['location']= $value['province'];
//                    $res[$count_res+$key]['testing_date']= $value['notification_number'];
                    $res[$count_res+$key]['batch_number']= $value['cdate'];
                    
                    if($value['qualified']==0)
                    {
                        
                        if(!empty($value['items']))
                        {
                            $res[$count_res+$key]['testing_result']= $value['items']." 超标 ";
                        }
                        else
                        {
                            $res[$count_res+$key]['testing_result']="";
                        }
                    }
                    else
                    {
                        $res[$count_res+$key]['testing_result']="";
                    }
                    
                }
            }
//            print_r($res_thirdparty);
//            $this->assign('results', $res);
            
        if(!empty($res))
        {

            $result['res']=$res;
            $result['err']=0;
            $result['msg']="成功获取数据";

        }
        else
        {
            $result['err']=1;
            $result['msg']="暂无更多数据";
            
        }
        echo json_encode($result);
//            print_r($res);

            
    }
    /*
     * 曝光台的首页列表数据
     */
    
     public function unsafe_list_by_page_for_index() {
        $pagecount = I('get.pagecount');
        
        $startposition = ($pagecount)*10;
        
        $res = array();
        
        $count_res = count($res);
        
        //找出关键字相关的记录
            $res_thirdparty = $this->get_thirdparty_product_by_name_for_unsafe_index($startposition,20);
            
            if(!empty($res_thirdparty))
            {
                foreach ($res_thirdparty as $key => $value) {
                    
                    $res[$count_res+$key]['name'] = $value['product_name'];
                    $res[$count_res+$key]['id'] = 0;
                    $res[$count_res+$key]['isurl']= 1;
                    $res[$count_res+$key]['url']= C('product_domain').U('M/Founding/show_thirdparty_data',array('id'=>$value['id']));
                    $res[$count_res+$key]['qualified']= $value['qualified'];
                    $res[$count_res+$key]['show_mark_icon']=  $this->_get_fouding_list_mark(1,$value['qualified'],3);
                    $res[$count_res+$key]['location']= $value['province'];
//                    $res[$count_res+$key]['testing_date']= $value['notification_number'];
                    $res[$count_res+$key]['batch_number']= $value['cdate'];
                    
                    if($value['qualified']==0)
                    {
                        
                        if(!empty($value['items']))
                        {
                            $res[$count_res+$key]['testing_result']= $value['items']." 超标 ";
                        }
                        else
                        {
                            $res[$count_res+$key]['testing_result']="";
                        }
                    }
                    else
                    {
                        $res[$count_res+$key]['testing_result']="";
                    }
                }
            }
//            print_r($res_thirdparty);
//            $this->assign('results', $res);
            
        if(!empty($res))
        {

            $result['res']=$res;
            $result['err']=0;
            $result['msg']="成功获取数据";

        }
        else
        {
            $result['err']=1;
            $result['msg']="暂无更多数据";
            
        }
        echo json_encode($result);
//            print_r($res);

            
    }
    
    private function get_thirdparty_product_by_name($keywords,$offset,$number) {
        //获取第三方数据库不合格商品
        
//        import("ORG.Util.Pinyin");
//        $py = new \PinYin();
//        
//        $result = $py->getAllPY("$keywords",',');
//        
//        $keywords_pys = str_replace(',', ' +', $result);
//        $keywords_pys ='+'.$keywords_pys;
        
        $Model = new \Think\Model();
        
        $res = $Model->query("select * from fd_third_party_product where product_name LIKE '%".$keywords."%' AND qualified=0 limit ".$offset.",$number");
        
//        $res = $Model->query("select * from fd_product_thirdparty where product_name LIKE '%".$keywords."%' AND qualified=0 AND match(product_name_pinyin) against('".$keywords_pys."' IN BOOLEAN MODE) limit $offset,$number");
//        print_r($res);
//        print_r($Model->getLastSql());
//        exit();
        return $res;
    }
    
    /*
     * 不安全的食品列表
     */
    private function get_thirdparty_product_by_name_for_unsafe_index($offset,$number) {
        //获取第三方数据库不合格商品


        $Model = new \Think\Model();
        $res = $Model->query("select * from fd_third_party_product where qualified=0 limit $offset,$number");
        return $res;
    }
    
    /*
     * 更新跟投的钱到项目金额去
     */
    private function _founding_finish_money_increase($fid,$money) {
        $DB = M('fundings');
        
        $DB->where("id=$fid")->setInc('finish',$money);
        
    }
    
    /*
    * 判断founding 是否满标，满的话，就改状态
    */
   private function _chk_if_donate_ok($fid) {
       $DB = M('fundings');
       $res = $DB->find($fid);
       /*
        * 判断项目是否是审核中的项目
        */
       if($res['state']==1)
       {
            if($res['finish']>=($res['emoney']+$res['smoney']))
            {
                $DB->id = $fid;
                $DB->state = 2;
                $DB->etime = I("server.REQUEST_TIME");
                $DB->save();
            }
       }
       
   }
   
   /*
    * 获取指定分类下的分类id
    */
   private function _get_package_relationship_by_sortid($sortid) {
       $DB = M("classify_package_relationship");
       $map['classify_id']=$sortid;
       $res = $DB->where($map)->select();
       
       if(!empty($res))
       {
           $packageids ="";
           foreach ($res as $key => $value) {
               $packageids .=$value['package_id'].",";
           }
           $result = substr($packageids,0,strlen($packageids)-1); 
           
           return $result;
       }
       else
       {
           return "";
       }
       
   }
   
   public function publish_agreement() {
       $this->display();
   }



    /*
     * Date: 2015-10-15
     * 
     * 第三方数据展示
     */
    public function show_thirdparty_data() {
        $id = I('get.id');
        $res =  M('third_party_product')->find($id);
        
//        $res =  M('product_thirdparty')->find($id);
//        $testing_result = explode("║", $res['unqualified_remark']);
//        $res['testing_result']= $testing_result[0];
        $testing_result="1"; //$testing_result = $value['check_result'];
        if(!empty($testing_result))
        {
            $res['testing_result']= $res['items'];
        }
        else
        {
            $res['testing_result']="";
        }
        $this->assign('product', $res);
        $this->display();
        
    }
    
    public function show_thirdparty_data_of_app() {
        $id = I('get.id');
//        $res =  M('product_thirdparty')->find($id);
        
        $res =  M('third_party_product')->find($id);
//        $testing_result = explode("║", $res['unqualified_remark']);
        
        $testing_result="1"; //$testing_result = $value['check_result'];
        if(!empty($testing_result))
        {
            $res['testing_result']= $res['items']."超标";
        }
        else
        {
            $res['testing_result']="";
        }
                    
//        $res['testing_result']= "";
        $this->assign('product', $res);
        $this->display();
        
    }
    
    /*
     * 更加mid 获取membername
     * 
     */
    private function get_name_by_mid($mid) {
        $DB = M('members');
        $res = $DB->find($mid);
//        判断用户名资料
        $username = $res['username'];
        if(preg_match("/1[3458]{1}\d{9}$/",$username))
        {
            $username = substr($username, 0, -4)."****";
        }
        return $username;
    }
    
    /*
     * 根据lab id 得到 lab name
     */
    private function get_name_by_institutionid($id) {
        $DB = M('institution');
        $res = $DB->find($id);
        return $res['name'];
    }
    
    /*
     * 根据sortid获取分类名称
     */
    private function get_name_by_sortid($id) {
        $DB = M('food_classify');
        $res = $DB->find($id);
        return $res['name'];
    }
    
    
    /*
     * 获取套餐资料
     */
    private function get_name_by_packageid($id) {
        /*
         * 判断id 是单个还是多少
         */
        $id_arr = explode(',', $id);
        $DB = M('fundings_package');
        $name="";
        foreach ($id_arr as $key => $value) {
            $res[$key] = $DB->find($value);
            $name .=",".$res[$key]['name'];
//            echo $name;
        }
        
        
        
        return substr($name, 1);
    }
    
    /*
     * 获取套餐的总价格
     */
    public function get_total_price_by_packageid($id) {
        /*
         * 判断id 是单个还是多少
         */
        $id_arr = explode(',', $id);
        $DB = M('fundings_package');
        foreach ($id_arr as $key => $value) {
            $res[$key] = $DB->find($value);
            $totalprice +=$res[$key]['price'];
//            echo $name;
        }
        return $totalprice/100;
    }
    
    
    /*
     * 获取套餐资料
     */
    private function get_package_by_id($id) {
        $DB = M('fundings_package');
        $res = $DB->find($id);
        return $res;
    }




    /*
     * 根据城市的code返回cityname
     */
    protected function get_cityname_by_citycode($citycode) {
        
        $DB = M('regions');
        
        $map['code']=$citycode;
        
        $res = $DB->where($map)->find();
        
        return $res['name'];
    }
    
    public function uploadimg() {
        $from = I('get.from');
        if(empty($from))
        {
            $from =0;

        }
        $this->assign('from', $from);

        $this->display();
    }
    
    /*
     * 获取项目的跟投支持人数
     */
    private function _get_founding_sponsor_count($fdid) {
        $map['status']=1;
        $map['fid']=$fdid;
        
        $DB = M("fundings_sponsor");
        $res = $DB->where($map)->count();
//        print_r($DB->getLastSql());
//        exit();
        return $res;
    }
    
        /*
     * 获取单个用户的头像信息
     */
    protected function _get_one_avatar($mid) {
        $member = $this->_get_member_info($mid);
        return $member['avatar'];
    }
    
    /*
     * 获取单个用户的昵称信息
     */
    protected function _get_member_nickname($mid)
    {
        $member = $this->_get_member_info($mid);
        $member_name=  $member['username'];
        if(mb_strlen($member_name)>8)
        {
            $member_name = mb_substr($member_name, 0,8,'utf-8');
        }
        return $member_name;
    }
    
    /*
     * 获取项目的图片展示列表
     * 
     * 
     * 
     * 临时要调整
     * 
     * 
     * 
     */
    private function get_one_thumb_list($detail_thumb_ids) {
//        $DB = M("fundings");
//        
//        $res = $DB->find($fdid);
//        
//        $thumb[]=$res['thumb'];
//        
//        
        
        $coverid = explode(",", $detail_thumb_ids);
        
        foreach($coverid as $key=>$value)
        {
            $thumb[] = M("fundings_image")->where('id='.$value)->getField('img_url');
        }
//        print_r($detail_thumb_ids);
        
        return $thumb;
        
        
    }
    
    /*
     * 获取封面图片
     */
    private function get_cover_of_samples($fdid) {
        $DB = M("fundings");
        
        $res = $DB->find($fdid);
        
        $coverid = explode(",", $res['sampleid']);
        
        foreach($coverid as $key=>$value)
        {
            $thumb[] = M("fundings_image")->find($value);
        }
        
//        $cover =  M("fundings_image")->find($coverid[0]);
        
//        print_r($cover);
        
//        return $cover['img_url'];
        
        return $thumb;
        
    }
    
    private function get_cover_of_testreport($fdid) {
        $DB = M("fundings");
        
        $res = $DB->find($fdid);
        
        $coverid = explode(",", $res['testreport_detail']);
        
        foreach($coverid as $key=>$value)
        {
            $thumb[] = M("fundings_image")->find($value);
        }
        
//        print_r($thumb);
        
        return $thumb;
        
    }
    
    
    /*
     * 红包模块
     * 分为几个大功能
     * 1. 红包领取
     * 2. 红包展示
     * 3. 红包使用
     * 
     */
    
    /*
     * 判断是否有红包领取
     * @param  openid
     * @return True/False;
     * 
     */
    private function _chk_if_can_get_redpack($openid,$fid,$create_openid) {
//        检查一下是否是同一个人
//        如果不是同一个人，要检查是否领取过这个fid的红包
        if($create_openid==$openid)
        {
            return FALSE;
        }
        else
        {
           if(!$this->_chk_if_double_get_redpack($openid, $fid))
           {
               return TRUE;
           }
           else
           {
               return FALSE;
           }
            
        }
    }
    
    
    /*
     * 判断是否领取过红包
     */
    private function _chk_if_double_get_redpack($openid,$fid)
    {
        $DB = M("redpack_receive_records");
        $map['openid']=$openid;
        $map['fid']=$fid;
        
        $res = $DB->where($map)->find();
        
        if(!empty($res))
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
    
    /*
     * 判断红包生成的参数是否有效
     * ok则返回true
     */
    private function _chk_redpack_param($fid,$random_code) {
        $DB = M("redpack_create_param");
        
        $map['fid']=$fid;
        $map['random_code']=$random_code;
        
        $res = $DB->where($map)->find();
        
        if(!empty($res))
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
        
    }




    /*
     * 生成红包参数记录
     */
    private function _create_redpack_param($fid,$openid) {
        $DB = M("redpack_create_param");
        
        $data['fid']=$fid;
        $data['openid']=$openid;
        $data['random_code']=  $this->_create_random_code(20);
        $data['ctime']=I("server.REQUEST_TIME");
        
        $id  = $DB->add($data);
        
        if($id)
        {
            return $data['random_code'];
        }
        else
        {
            return FALSE;
        }
    }
    
    
    /*
     * 生成红包的可领取记录
     */
    private function _create_redpack_records($random_code,$redpack_code,$fid) {
        $DB = M("redpack_create_records");
        $data['random_code']=$random_code;
        $data['redpack_code']=$redpack_code;
        $data['ctime']=I("server.REQUEST_TIME");
        $data['etime']=$data['ctime']+60*60*24*30*2;
        $data['fid']=$fid;
        
        $slogan[0]="食品安全我做主，大家一起参与食品检测~";
        $slogan[1]="你不是一个人在战斗，大家一起行动起来~";
        $slogan[2]="支持！远离毒食品的危害~";
        
        $data['slogan'] = $slogan[rand(0,2)];
        
        //计算红包的大小
        $data['cash']=$this->_create_redpack_cash();
        
        //通过random_code 查找发起人 openid
        $openid = M("redpack_create_param")->where(array('random_code'=>$random_code))->getField("openid");
        
        $data['openid']=$openid;
        
        $id = $DB->add($data);
        
        
        if($id)
        {
            return $id;
        }
        else {
            return FALSE;
        }
        
    }
    
    
    /*
     * 生成红包的金额大小
     */
    private function _create_redpack_cash()
    {
        $cash_array=array('1', '1', '1', '1', '1', '1', '1', '1', '5' ,'5');
        
        $n = rand(0,9);
        return $cash_array[$n];
    }
    
    public function ip() {
        $ip = get_client_ip();
        echo $ip;
    }


    /*
     * 生成红包的被领取记录
     */
    private function _bonding_redpack_member($mid,$rp_id,$openid,$etime)
    {
        $DB = M("redpack_receive_records");
        
        
        $data['mid']=$mid;
        $data['openid']=$openid;
        $data['etime']=$etime;
        $data['rp_id']=$rp_id;
        $data['ctime']=I("server.REQUEST_TIME");
        $data['utime']=I("server.REQUEST_TIME");
        
        
    }
    
    
    /*
     * 生成随机码
     */
    private function _create_random_code($length)
    {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
         $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }
    
    
    public function test() {
        $res = $this->_create_random_code(20);
        echo $res;
    }
    
    
    
    
    
    
    
}
